//
//  UITextView+Emoticon.swift
//  EmotionIcon
//
//  Created by 朴裕识 on 16/1/6.
//  Copyright © 2016年 Apple. All rights reserved.
//

import UIKit

extension UITextView {
    func getTextContainingEmoticon() -> String {
        var text = ""
        attributedText.enumerateAttributesInRange(NSRange(location: 0, length: attributedText.length), options: NSAttributedStringEnumerationOptions(rawValue: 0)) { (result, range, _) -> Void in
            
            if let attachment = result["NSAttachment"] as? YSPTextAttachment {
                //到了这里说明有图片
                text += attachment.chs!
                
            } else {
                //到了这里说明只有文字和emoji
                let tempText = (self.attributedText.string as NSString).substringWithRange(range)
                text += tempText
            }
        }
        return text
    }
    
    func insertEmoticon(emoticonModel: YSPEmoticonModel) {
        //先判断，如果是删除按钮，就删除文本，图片表情，emoji
        if emoticonModel.removeEmoticon {
            deleteBackward()
        }
        
        //添加emoji表情
        if let emoji = emoticonModel.emoji {
            insertText(emoji)
            return
        }
        
        //添加其他的图片表情
        if let pngPath = emoticonModel.pngPath {
            //创建图片附件
            let attachment = YSPTextAttachment()
            attachment.chs = emoticonModel.chs
            attachment.image = UIImage(contentsOfFile: pngPath)
            
            let temp = font!.lineHeight
            attachment.bounds = CGRect(x: 0, y: -(temp * 0.28), width: temp, height: temp)
            
            let attrText = NSMutableAttributedString(attributedString: NSAttributedString(attachment: attachment))
            //连续添加图片表情的话，会发现后边的表情变小，原因是没有给属性文本设置font
            attrText.addAttribute(NSFontAttributeName, value: font!, range: NSRange(location: 0, length: 1))
            
            //获取现有的文本
            let currentAttributedText = NSMutableAttributedString(attributedString: attributedText)
            let range = selectedRange
            currentAttributedText.replaceCharactersInRange(range, withAttributedString: attrText)
            
            attributedText = currentAttributedText
            
            //重新设置光标的位置
            selectedRange = NSRange(location: range.location + 1, length: 0)
            
            NSNotificationCenter.defaultCenter().postNotificationName(UITextViewTextDidChangeNotification, object: self)
            delegate?.textViewDidChange?(self)
        }
    }

}
